package cn.csc.module.distribute.service.audit;

import cn.csc.framework.common.enums.UserTypeEnum;
import cn.csc.framework.common.pojo.PageResult;
import cn.csc.framework.common.util.collection.CollectionUtils;
import cn.csc.module.distribute.controller.admin.audit.vo.DistributorAuditCreateReqVO;
import cn.csc.module.distribute.controller.admin.audit.vo.DistributorAuditPageReqVO;
import cn.csc.module.distribute.controller.admin.audit.vo.DistributorAuditUpdateReqVO;
import cn.csc.module.distribute.convert.audit.DistributorAuditConvert;
import cn.csc.module.distribute.dal.dataobject.audit.DistributorAuditDO;
import cn.csc.module.distribute.dal.dataobject.distributor.DistributorDO;
import cn.csc.module.distribute.dal.mysql.audit.DistributorAuditMapper;
import cn.csc.module.distribute.dal.mysql.distributor.DistributorMapper;
import cn.csc.module.infra.api.file.FileApi;
import cn.csc.module.member.api.user.MemberUserApi;
import cn.csc.module.member.api.user.dto.MemberUserRespDTO;
import cn.csc.module.system.api.social.SocialClientApi;
import cn.csc.module.system.api.social.dto.SocialWxaCodeUnlimitReqDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.csc.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csc.module.distribute.enums.ErrorCodeConstants.DISTRIBUTOR_AUDIT_NOT_EXISTS;

/**
 * 分销员审核记录 Service 实现类
 *
 * @author liuchuang
 */
@Slf4j
@Service
@Validated
public class DistributorAuditServiceImpl implements DistributorAuditService {

    @Resource
    private DistributorAuditMapper distributorAuditMapper;

    @Resource
    private DistributorMapper distributorMapper;

    @Resource
    private FileApi fileApi;

    @Resource
    private SocialClientApi socialClientApi;

    @Resource
    private MemberUserApi memberUserApi;

    @Value("${spring.profiles.active}")
    private String profile;


    @Transactional
    @Override
    public BigInteger createDistributorAudit(DistributorAuditCreateReqVO createReqVO) {
        log.info("createDistributorAudit req: {}",createReqVO);
        // 插入
        DistributorAuditDO distributorAudit = DistributorAuditConvert.INSTANCE.convert(createReqVO);
        distributorAuditMapper.insert(distributorAudit);
        // 审核通过
        if (distributorAudit.getAuditStatus() == 1){
            DistributorDO distributorDO = distributorMapper.selectById(distributorAudit.getDistributorId());
            // 生成推广二维码
            SocialWxaCodeUnlimitReqDTO reqDTO = new SocialWxaCodeUnlimitReqDTO();
            reqDTO.setUserType(UserTypeEnum.MEMBER.getValue());
            reqDTO.setScene(distributorDO.getInviteCode());
            reqDTO.setPage("pages/index/index");
            reqDTO.setEnvVersion("uat".equals(profile) ? "trial" : "release");
            byte[] data = socialClientApi.getWxaCodeUnlimitBytes(reqDTO).getCheckedData();
            log.info("createDistributorAudit data: {}",data);
            // 上传
            String file = fileApi.createFile(data);
            log.info("createDistributorAudit file: {}",file);
            distributorDO.setDistributeWxCode(file);
            log.info("createDistributorAudit distributorDO: {}",distributorDO);
            distributorMapper.updateInviteInfo(distributorDO);
        }
        // 更新分销员的审核状态和审核时间
        distributorMapper.updateAuditStatus(createReqVO.getDistributorId(), createReqVO.getAuditStatus());
        // 返回
        return distributorAudit.getId();
    }

    @Override
    public void updateDistributorAudit(DistributorAuditUpdateReqVO updateReqVO) {
        // 校验存在
        validateDistributorAuditExists(updateReqVO.getId());
        // 更新
        DistributorAuditDO updateObj = DistributorAuditConvert.INSTANCE.convert(updateReqVO);
        distributorAuditMapper.updateById(updateObj);
    }

    @Override
    public void deleteDistributorAudit(BigInteger id) {
        // 校验存在
        validateDistributorAuditExists(id);
        // 删除
        distributorAuditMapper.deleteById(id);
    }

    private void validateDistributorAuditExists(BigInteger id) {
        if (distributorAuditMapper.selectById(id) == null) {
            throw exception(DISTRIBUTOR_AUDIT_NOT_EXISTS);
        }
    }

    @Override
    public List<DistributorAuditDO> getByUserId(BigInteger userId){
        List<DistributorAuditDO> auditDOS = distributorAuditMapper.selectByUserId(userId);
        List<Long> creators = auditDOS.stream().map(DistributorAuditDO::getCreator).map(Long::valueOf).distinct().collect(Collectors.toList());
        log.info("getByUserId creators: {}", creators);
        List<MemberUserRespDTO> users = memberUserApi.getUserList(creators).getCheckedData();
        log.info("getByUserId users: {}", users);
        Map<Long, String> userMap = CollectionUtils.convertMap(users, MemberUserRespDTO::getId, v -> StringUtils.hasLength(v.getName()) ? v.getName() : v.getNickname());
        log.info("getByUserId userMap: {}", userMap);
        auditDOS.forEach(a -> a.setCreator(userMap.get(Long.valueOf(a.getCreator()))));
        return auditDOS;
    }

    @Override
    public long updateByUserId(BigInteger userId){
        return distributorAuditMapper.updateByUserId(userId);
    }

    @Override
    public PageResult<DistributorAuditDO> getDistributorAuditPage(DistributorAuditPageReqVO pageReqVO) {
        return distributorAuditMapper.selectPage(pageReqVO);
    }


}
